import { createConnection } from 'typeorm';
import { User } from '../src/modules/user/entities/user.entity';
import { Activity } from '../src/modules/activity/entities/activity.entity';
import { ActivityFavorite } from '../src/modules/activity/entities/activity-favorite.entity';
import { Comment } from '../src/modules/comment/entities/comment.entity';
import { SmsCode } from '../src/modules/sms/entities/sms-code.entity';
import { OperationLog } from '../src/modules/operation-log/entities/operation-log.entity';
import { config } from 'dotenv';

config();

async function resetDatabase() {
  const connection = await createConnection({
    type: 'mysql',
    host: process.env.DB_HOST || 'localhost',
    port: Number(process.env.DB_PORT) || 3306,
    username: process.env.DB_USERNAME || 'root',
    password: process.env.DB_PASSWORD || '123456',
    database: process.env.DB_DATABASE || 'hdq-news',
    entities: [User, Activity, ActivityFavorite, Comment, SmsCode, OperationLog],
    synchronize: true,
    dropSchema: true
  });

  try {
    console.log('开始重置数据库...');
    // 等待连接初始化完成
    await connection.synchronize(true);
    console.log('数据库架构已重置');

    // 创建基础数据
    const userRepository = connection.getRepository(User);

    // 创建一个默认管理员用户
    const adminUser = userRepository.create({
      username: 'admin',
      nickname: '管理员',
      phone: '13800138000',
      password: '$2b$10$EpRnTzVlqHNP0.fUbXUwSOyuiXe/QLSUG6xNekdHgTGmrpHEfIoxm', // 密码是 'password'
      gender: 1,
      status: 1,
      isPhoneVerified: true,
      isEmailVerified: true
    });

    await userRepository.save(adminUser);
    console.log('创建了默认管理员用户');

    console.log('数据库重置完成');
  } catch (error) {
    console.error('重置数据库时出错:', error);
  } finally {
    await connection.close();
  }
}

resetDatabase()
  .then(() => process.exit(0))
  .catch(error => {
    console.error(error);
    process.exit(1);
  });